<?php
namespace api\modules\v1\controllers;

use api\modules\v1\models\user\User;
use PHPUnit\Runner\AfterIncompleteTestHook;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;
use yii\rest\ActiveController;
use Yii;
/**
 * Default controller for the `v1` module
 */
class DefaultController extends ActiveController
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function init()
    {
        $user = (new User())->checkUserNoExp();
        (new \common\models\user\User())->setPosition($user);

        parent::init(); // TODO: Change the autogenerated stub
    }

    public function behaviors()
    {
        return ArrayHelper::merge([
            [
                'class' => Cors::className(),
                'cors' => [
                    'Origin' => ["*"],
                    'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'OPTIONS', 'PATCH', 'DELETE'],
                    'Access-Control-Request-Headers' => [
                        'access-token', 'Content-Type', 'Accept', 'X-Requested-With', 'Origin', 'Cache-Control', 'Postman-token',
                        'version', 'terminal', 'platform','version-terminal','latitude','longitude'
                    ],
                    'Access-Control-Max-Age' => 600,
                ]
            ]
        ], parent::behaviors());
    }

    public function actionOptions() {
        return true;
    }

    public function afterAction($action, $result) {
        $data = [
            "method" => \Yii::$app->request->method,
            'module' => $action->controller->module->id,
            'controller' => $action->controller->id,
            'action' => $action->id,
            'path' => \Yii::$app->request->pathInfo,
            "times" => 0,
            "maxTime" => \Yii::getLogger()->getElapsedTime(),
            "minTime" => \Yii::getLogger()->getElapsedTime(),
        ];

        $redis = \Yii::$app->get("redis");

        $key = "API_STATISTIC:{$data['module']}:{$data['controller']}:{$data['action']}:{$data['method']}";

        $exist = $redis->exists($key);

        if ($exist == 1) {
            $redis->hincrby($key, "times", 1);
            $redis->hset($key, "minTime", $data['minTime']);
        } else {
            foreach ($data as $k => $v) {
                $redis->hset($key, $k, $v);
            }
        }

        return $result;
    }

    public function actions()
    {
        $action = parent::actions(); // TODO: Change the autogenerated stub
        unset($action['index']);
        unset($action['create']);
        unset($action['update']);
        unset($action['delete']);
        return $action;
    }
}
